package com.xiecong.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xiecong.mapper.ClazzMapper;
import com.xiecong.mapper.StudentMapper;
import com.xiecong.pojo.Clazz;
import com.xiecong.pojo.ClazzQueryParam;
import com.xiecong.pojo.PageResult;
import com.xiecong.service.ClazzServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClazzServerImpl implements ClazzServer {

    @Autowired
    private ClazzMapper clazzMapper;

    @Autowired
    private StudentMapper studentMapper;

    /**
     * 新增班级信息
     * @param clazz
     * @return
     */
    @Override
    public void add(Clazz clazz) {
        LocalDateTime now = LocalDateTime.now();
        clazz.setCreateTime(now);
        clazz.setUpdateTime(now);
        clazzMapper.insert(clazz);
    }


    /**
     * 查询所有班级信息
     *
     * @return
     */
    @Override
    public List<Clazz> findAll() {
        List<Clazz> clazzs = clazzMapper.findAll();
        return clazzs;
    }


    /**
     * 分页按条件查询班级列表
     */

    @Override
    public PageResult<Clazz> pageQuery(ClazzQueryParam clazzQueryParam) {
        //1、传入page和pageSize
        PageHelper.startPage(clazzQueryParam.getPage(),clazzQueryParam.getPageSize());
        //2、执行查询，会被分页
        List<Clazz> clazzes = clazzMapper.pageQuery(clazzQueryParam);
        //3、解析结果
        Page<Clazz> pageinfo = (Page<Clazz>)clazzes;
        //4、封装到PageResult返回
        return new PageResult<Clazz>(pageinfo.getTotal(),pageinfo.getResult());
    }


    /**
     * 修改班级信息-数据回显-根据id查询
     */
    @Override
    public Clazz findById(Integer id) {
        Clazz clazz = clazzMapper.findById(id);
        return clazz;
    }


    /**
     * 修改班级信息
     */
    @Override
    public void updateById(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.updateById(clazz);
    }


    /**
     * 删除班级信息
     * @param id
     */
    @Override
    public void deleteById(Integer id) {
        List<Integer> allClazzId = studentMapper.findAllClazzId();
        if(!allClazzId.contains(id)) {
            clazzMapper.deleteById(id);
        }else{
            throw new RuntimeException("对不起，当前班级下有学生，不能直接删除！");
        }
    }
}
